<script lang="ts" setup>
import { ref } from 'vue'
import Button from './Button.vue'
import logo from '~/assets/images/logo.png'
import { logger } from '~/utils/logger'
import { accountLogin } from '@/service/http'
import { HexMD5 } from '@/utils/md5'

// 定义事件，用于与父组件通信
const emit = defineEmits<{
  loginSuccess: [username: string]
}>()

// 用户名和密码
const username = ref('')
const password = ref('')
// 错误提示
const errorMsg = ref('')
// 登录加载状态
const isLoading = ref(false)

// 创建专用的登录Logger
const loginLogger = logger.createChild('Login')

/**
 * 登录处理函数
 * 实际开发中可以替换为真实的API接口调用
 */
async function handleLogin() {
  loginLogger.info('开始登录流程')

  // 清空之前的错误信息
  errorMsg.value = ''

  // 基本验证
  if (!username.value.trim()) {
    errorMsg.value = '请输入用户名'
    loginLogger.warn('登录失败：用户名为空')
    return
  }

  if (!password.value.trim()) {
    errorMsg.value = '请输入密码'
    loginLogger.warn('登录失败：密码为空')
    return
  }

  // 设置加载状态
  isLoading.value = true

  const params = {
    loginid: username.value,
    password: HexMD5(password.value)
  }

  localStorage.setItem('PLUGINS_ACCOUNT_INFO', JSON.stringify(params))

  accountLogin(params).then((res: any) => {
    if (res.success) {

      const { personid, ifforbidden, personName } = res.rows || {}

      if (ifforbidden) {
        errorMsg.value = '账号已禁用, 请联系管理员'
        loginLogger.warn('登录失败：账号已禁用')
        return
      }

      localStorage.setItem('jhjk_login_id', personid)

      localStorage.setItem('MZ_PLUGIN_TOKEN_KEY', res.token)

      emit('loginSuccess', personName)

    } else {
      errorMsg.value = res.message || '登录失败'
    }
  }).catch(err => {
    errorMsg.value = '登录失败，请稍后重试!'
    loginLogger.error(err)
  }).finally(() => {
    isLoading.value = false
  })


}

/**
 * 处理回车键登录
 */
function handleKeyPress(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    loginLogger.debug('检测到回车键，触发登录')
    handleLogin()
  }
}
</script>

<template>
  <div class="login-form">

    <!-- Logo -->
    <img class="login-logo" :src="logo" alt="Logo" />

    <div class="login-title">登录医生助手</div>

    <!-- 用户名输入框 -->
    <input v-model="username" type="text" placeholder="请输入账号" class="login-input" @keypress="handleKeyPress" :disabled="isLoading" />

    <!-- 密码输入框 -->
    <input v-model="password" type="password" placeholder="请输入密码" class="login-input" @keypress="handleKeyPress" :disabled="isLoading" />

    <!-- 错误提示 -->
    <div v-if="errorMsg" class="login-error">{{ errorMsg }}</div>

    <!-- 登录按钮 -->
    <Button @click="handleLogin" :loading="isLoading" :disabled="isLoading" type="default" class="login-button">
      登录
    </Button>
  </div>
</template>

<style scoped>
.login-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
}

.login-logo {
  margin-top: 60px;
  width: 144px;
  height: auto;
}

.login-title {
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 1rem;
  color: #1f2937;
}

.login-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  outline: none;
  box-sizing: border-box;
  transition: all 0.2s ease;
  font-size: 14px;
}

.login-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.login-input:disabled {
  background-color: #f9fafb;
  cursor: not-allowed;
  opacity: 0.6;
}

.login-button {
  width: 100%;
  margin-top: 8px;
}

.login-error {
  color: #ef4444;
  font-size: 12px;
  text-align: center;
  padding: 8px;
  background-color: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}
</style>